﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Vkontakte.Api.Database;

namespace Vkontakte.Api
{
	public static class ImageDownloader
	{
		private static IImageCache _cache;
		public static void DownloadImage(string url,Action<bool,byte[]> callback )
		{
			DownloadImage( url, null, callback );
		}

		public static void DownloadImage(string url,CookieContainer cookie, Action<bool,byte[]> callback )
		{
			if (_cache!=null)
			{
				byte[] cached= _cache.GetImage( url );
				if (cached!=null)
				{
					callback( true, cached);
					return;
				}
			}
			// Jpeg не уменьшается в размере при запаковке
			HttpWebRequest request = (HttpWebRequest)WebRequest.Create( url );
			if (cookie!=null)
			{
				request.CookieContainer = cookie; 
			}
			DownloadTask task = new DownloadTask() {Callback = callback, Request = request, Url = url};
			request.BeginGetResponse( Callback, task );
		}


		static void Callback(IAsyncResult result)
		{
			byte[] ret = null;
			bool ok = false;
			int imgLen = 0;
			DownloadTask task = result.AsyncState as DownloadTask;
			if (task==null)
			{
				return;
			}
			try
			{
				WebResponse response= task.Request.EndGetResponse(result);
				if (response.ContentType=="image/jpeg")
				{
					
				}
				Stream s = response.GetResponseStream();


				
				MemoryStream m = new MemoryStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = s.Read(buffer, 0, 1024)) > 0)
				{
					m.Write(buffer, 0, len);
				}
				byte[] temp=m.GetBuffer();
				ret = new byte[m.Length];
				Array.Copy( temp, ret, m.Length );
				
				ok = true;
			}
			catch ( Exception )
			{
			}
			task.Callback(ok, ret);
			if (_cache != null)
			{
				_cache.SaveImage(task.Url, ret);
			}
		}

		public static void AttachImageCache(IImageCache cache)
		{
			_cache = cache;
		}

		private class DownloadTask
		{
			public string Url;
			public HttpWebRequest Request;
			public Action<bool, byte[]> Callback;
		}
	}
}
